<?php


namespace app\api\model;
use think\Model;

class Posts extends Model
{
    protected $name = 'posts';

    //2023-06-12 07:04:21 2023-08-13 17:04:21
    public function index($params,$where){
        $sql=self::alias('p')->where($where)->field('m.avatar,m.id merchant_id,m.name,m.address_link,m.terminal,p.id,p.title,p.sub_title,p.label,p.source,p.source_type,p.start_time,p.end_time,p.content,p.poster,p.duration,p.create_time');
        $terminal=$params['terminal'];
        if($params['sub_category']){
            $sub_category=explode(',',$params['sub_category']);
            $sql=$sql->where(function ($query) use($sub_category){
                foreach ($sub_category as $key=>$val){
                    if($key==0){
                        $query=$query->where('find_in_set(:category_id,m.sub_category)',['category_id'=>$val]);
                    }else{
                        $query->whereOr('find_in_set(:category_id,m.sub_category)',['category_id'=>$val]);
                    }
                }
            });
        }

        if($params['keyword']){
            $keyword=$params['keyword'];
            $sql=$sql->where(function ($query) use($keyword){
                $query->where('p.title','LIKE','%'.$keyword.'%')
                    ->whereOr('p.content','LIKE','%'.$keyword.'%');
            });
        }
        $sql=$sql->when($params['terminal'],function ($query) use($terminal){
            $query->whereIn('m.terminal',$terminal);
        });

        if($params['deadline']){
            $map=[
                ['p.start_time','<',$params['real_start_time']],
                ['p.end_time','>',$params['real_end_time']],
            ];
            $sql=$sql->whereNotNull('p.start_time')->where(function ($query) use($map,$params){
                $query->where('p.start_time',['>=',$params['real_start_time']],['<',$params['real_end_time']],'and')
                    ->whereOr('p.end_time',['>=',$params['real_start_time']],['<',$params['real_end_time']],'and')
                    ->whereOr([$map]);
            });
        }
        $result=$sql->leftJoin('merchant m','m.id=p.merchant_id')
            ->order('p.create_time','desc')
            ->page($params['page'],$params['pageSize'])
            ->select()
            ->toArray();

        $count=$this->getCount($params,$where);
//        echo self::getLastSql();die;
        $data['result']=$result;
        $data['total']=$count;
        $data['pageCount']=ceil($count/$params['pageSize']);
        return $data;
    }


    private function getCount($params,$where){
        $terminal=$params['terminal'];

        $sql=self::alias('p')->where($where);

        if($params['sub_category']){
            $sub_category=explode(',',$params['sub_category']);
            $sql=$sql->where(function ($query) use($sub_category){
                foreach ($sub_category as $key=>$val){
                    if($key==0){
                        $query=$query->where('find_in_set(:category_id,m.sub_category)',['category_id'=>$val]);
                    }else{
                        $query->whereOr('find_in_set(:category_id,m.sub_category)',['category_id'=>$val]);
                    }
                }
            });
        }

        if($params['keyword']){
            $keyword=$params['keyword'];
            $sql=$sql->where(function ($query) use($keyword){
                $query->where('p.title','LIKE','%'.$keyword.'%')
                    ->whereOr('p.content','LIKE','%'.$keyword.'%');
            });
        }

        $sql=$sql->when($params['terminal'],function ($query) use($terminal){
            $query->whereIn('m.terminal',$terminal);
        });
        if($params['deadline']){
            $map=[
                ['p.start_time','<',$params['real_start_time']],
                ['p.end_time','>',$params['real_end_time']],
            ];
            $sql=$sql->whereNotNull('p.start_time')->where(function ($query) use($map,$params){
                $query->where('p.start_time',['>=',$params['real_start_time']],['<',$params['real_end_time']],'and')
                    ->whereOr('p.end_time',['>=',$params['real_start_time']],['<',$params['real_end_time']],'and')
                    ->whereOr([$map]);
            });
        }
        $count=$sql->leftJoin('merchant m','m.id=p.merchant_id')
            ->count();

        return $count;
    }

    public function info($id){
        $info=self::where('id',$id)->find();
        if(!$info) {
            return false;
        }
        $info=$info->toArray();
        if($info['label']){
            $info['label'] = Label::where('id',$info['label'])->field('id,name,color')->find()->toArray();
        }else{
            $info['label']='';
        }
        $merchant_info=Merchant::where('id',$info['merchant_id'])->field('avatar,name,airport,terminal,address_link')->find()->toArray();
        $info['airport_name']=Airport::where('id',$merchant_info['airport'])->value('name');
        $sources=json_decode($info['source'],true);
        if($sources){
            unset($info['source']);
            foreach ($sources as $source){
                $info['source'][]=get_file_path($source);
            }
        }else{
            $info['source']=[];
        }
        if($merchant_info['avatar']){
            $info['avatar']=get_file_path($merchant_info['avatar']);
        }else{
            $info['avatar']=get_file_path(config('data.merchant_avatar_default'));
        }
        $info['name']=$merchant_info['name'];
        $info['terminal']=$merchant_info['terminal'];
        $info['address_link']=$merchant_info['address_link'];
        if($info['source_type']==2){
            $info['poster']=get_file_path($info['poster']);
        }
        $info['event_time']='';
        if($info['start_time']){
            $info['event_time']=handleEventTime($info['start_time'],$info['end_time']);
        }
        $info['like_count']=PostLike::where('post_id',$id)->count();

        return $info;
    }

    public function getMerchant($id){
        return self::where('id',$id)->value('merchant_id');
    }


    /**
     * @param array $where
     * @param array $params
     */
    public function getPosts(array $where,array $params){
        $lists=self::alias('p')->where($where)
            ->field('p.id,title,sub_title,label,p.start_time,p.end_time,content,source,source_type,poster,duration,p.create_time,m.address_link')
            ->leftJoin('merchant m', 'm.id=p.merchant_id')
            ->order('p.create_time','desc')
            ->page($params['page'],$params['pageSize'])
            ->select()->toArray();

        $total=$this->postsCount($where);

        $data['result']=$lists;
        $data['total']=$total;
        $data['pageCount']=ceil($data['total']/$params['pageSize']);
        return $data;
    }

    private function postsCount(array $where){
        return self::alias('p')->where($where)->count();
    }

    public function myLike(array $params){
        $lists=self::alias('p')
            ->where(['pl.mid'=>$params['id'],'pl.type'=>$params['user_type'],'p.status'=>1])
            ->leftJoin('post_like pl','pl.post_id=p.id')
            ->leftJoin('merchant m','p.merchant_id=m.id')
            ->field('m.avatar,m.name,m.id merchant_id,m.terminal,m.address_link,m.airport,p.id,title,sub_title,label,p.start_time,p.end_time,content,source,source_type,poster,duration,p.create_time')
            ->order('pl.create_time','desc')
            ->page($params['page'],$params['pageSize'])
            ->select()->toArray();
        $total=$this->myLikeCount($params);
        $data['result']=$lists;
        $data['total']=$total;
        $data['pageCount']=ceil($data['total']/$params['pageSize']);
        return $data;
    }

    private function myLikeCount(array $params){
        return self::alias('p')
            ->leftJoin('post_like pl','pl.post_id=p.id')
            ->where(['pl.mid'=>$params['id'],'pl.type'=>$params['user_type'],'p.status'=>1])
            ->count();
    }

    public function getTitle($keyword){
        return self::whereLike('title',$keyword.'%')->distinct(true)->field('title')->limit(20)->select()->toArray();
    }
}